package team.kas.anime.controller;

import cn.dsna.util.images.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import team.kas.anime.pojo.Result;
import team.kas.anime.pojo.User;
import team.kas.anime.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/home")
public class HomeController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index(HttpServletRequest request){

        User user = (User)request.getSession().getAttribute("user");
        if(user != null){
            request.getSession().setMaxInactiveInterval(24*60*60);
            return "index";
        }else {
            return "login";
        }

    }

    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response){

        ValidateCode validateCode =new ValidateCode(160,40,4,50);
        String code = validateCode.getCode();
        request.getSession().setAttribute("code",code);
        request.getSession().setMaxInactiveInterval(300);
        try {
            validateCode.write(response.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String remember, String username, String password, String code, HttpServletRequest request){

        return userService.login(remember,username,password,code,request);
    }

    @RequestMapping("/main")
    public String main(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        String rId = user.getRemark();
        if(rId.equals("2")){
            return "index";
        }else {
            return "userIndex";
        }
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @RequestMapping("/mobileCode")
    @ResponseBody
    public Result mobileCode(String phone,HttpServletRequest request){

        return userService.mobileCode(phone,request);
    }

    @RequestMapping("/upImg")
    @ResponseBody
    public Result upImg(MultipartFile file,HttpServletRequest request){
        return userService.upImg(file,request);
    }

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/home")
    public String home(){
        return "home";
    }

    @RequestMapping("/loginOut")
    public String loginOut(HttpServletRequest request){
        request.getSession().invalidate();
        return "login";
    }
}
